package com.qianya.weishi_server.utils;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

/**
 * 纳秒值，值不准确
 * 同一毫秒，纳秒值是增加的（不是一定增加），可能为负
 */
public class Nanosecond {

    private long lastMilliTime;

    private long lastNanoTime;

    public synchronized long nanosecond(final long milliTime) {
        if (lastMilliTime < milliTime) {
            lastMilliTime = milliTime;
            lastNanoTime = System.nanoTime();
        }
        return System.nanoTime() - lastNanoTime;
    }

    public long nanosecond() {
        long milliTime = System.currentTimeMillis();
        return nanosecond(milliTime);
    }

    public static String presentTime() {
        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MILLISECOND, 0);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        return sdf.format(new Date(Long.parseLong(String.valueOf(calendar.getTimeInMillis()))));
    }

    /**
     * 获取当前年份
     *
     * @return
     */
    public static int getCurrYear() {
        Calendar currCal = Calendar.getInstance();
        return currCal.get(Calendar.YEAR);
    }

    /**
     * 获取当年的第一天
     *
     * @return
     */
    public static Date getCurrYearFirst() {
        Calendar currCal = Calendar.getInstance();
        int currentYear = currCal.get(Calendar.YEAR);
        return getYearFirst(currentYear);
    }

    /**
     * 获取某年第一天日期
     *
     * @param year 年份
     * @return Date
     */
    public static Date getYearFirst(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        Date currYearFirst = calendar.getTime();
        return currYearFirst;
    }

    /**
     * 获取当年最后一天日期
     *
     * @param year 年份
     * @return Date
     */
    public static Date getYearLast(int year) {
        Calendar calendar = Calendar.getInstance();
        calendar.clear();
        calendar.set(Calendar.YEAR, year);
        calendar.roll(Calendar.DAY_OF_YEAR, -1);
        Date currYearLast = calendar.getTime();
        return currYearLast;
    }

}
